import React, { Component } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Form,
  Input,
  DatePicker,
  Button,
  Card,
  InputNumber,
  Radio,
  Row,
  Col,
  message,
  Modal,
  Text,
  Upload,
  Icon,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import SelectDev from '../../components/UpLoadForm/SelectDev';
import { cityUrls } from '../../utils/city';

const FormItem = Form.Item;
const { Search } = Input;
@connect(({ devreport }) => ({
  devreport,
}))
@Form.create()
export default class DevReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      picUrlsArray: [],
      vidUrlsArray: [],
    };
  }
  componentDidMount() {}
  setVisible = value => {
    this.setState({
      modalVisible: value,
    });
  };

  handleChange = info => {
    let fileList = [...info.fileList];

    // 1. Limit the number of uploaded files
    // Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-2);

    // 2. Read from response and show file link
    fileList = fileList.map(file => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });

    this.setState({ picUrlsArray: fileList });
  };

  handleVidChange = info => {
    let fileList = [...info.fileList];

    // 1. Limit the number of uploaded files
    // Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-2);

    // 2. Read from response and show file link
    fileList = fileList.map(file => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.url;
      }
      return file;
    });

    this.setState({ vidUrlsArray: fileList });
  };
  onSearch = value => {
    const searchType = this.props.form.getFieldValue('searchType');
    if (searchType === 0) {
      this.props.dispatch({
        type: 'devreport/fetch',
        payload: { vehLicplateNo: value },
      });
    } else {
      this.props.dispatch({
        type: 'devreport/fetch',
        payload: { devUuid: value },
      });
    }
    this.setVisible(true);
  };

  setFormValue = record => {
    this.props.form.setFieldsValue({
      devUuid: record.devUuid,
      vehLicplateNo: record.vehLicplateNo,
      compName: record.compName,
      devName: record.devName,
      mainDriver: record.mainDriver,
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { devUuid, reporter, orgName, problemDescr } = values;
        const { picUrlsArray, vidUrlsArray } = this.state;
        let postvalue = { devUuid, reporter, orgName, problemDescr };
        if (picUrlsArray.length > 0) {
          let picUrls = '';
          for (let i = 0; i < picUrlsArray.length; i++) {
            picUrls = picUrls + picUrlsArray[i].response.uploadFile.fileUrl + ';';
          }
          postvalue = { ...postvalue, picUrls };
        }
        if (vidUrlsArray.length > 0) {
          let vidUrls = '';
          for (let i = 0; i < vidUrlsArray.length; i++) {
            vidUrls = vidUrls + vidUrlsArray[i].response.uploadFile.fileUrl + ';';
          }
          postvalue = { ...postvalue, vidUrls };
        }
        //console.log('postvalue', postvalue);
        this.props.dispatch({
          type: 'devreport/submit',
          payload: postvalue,
          callback: () => {
            message.success('报修成功');
            // const encodeName = encodeURI(progName);
            this.props.history.push(`/devmaintain/devfix`);
          },
        });
      }
    });
  };

  render() {
    const {
      submitting,
      devreport: { devlist },
    } = this.props;
    //console.log("devlist", devlist)
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };
    return (
      <PageHeaderLayout title="设备报修">
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <Row>
              <Col span={8}>
                <FormItem {...formItemLayout} label="类型">
                  {getFieldDecorator('searchType', {
                    initialValue: 0,
                  })(
                    <Radio.Group>
                      <Radio value={0}>车牌号</Radio>
                      <Radio value={1}>设备ID</Radio>
                    </Radio.Group>
                  )}
                </FormItem>
              </Col>
              <Col span={16}>
                <FormItem {...formItemLayout} label="关键字">
                  {getFieldDecorator('keyword', {
                    rules: [
                      {
                        required: true,
                        message: '请输入关键字',
                      },
                    ],
                  })(
                    <Search
                      placeholder="请输入关键字"
                      enterButton="搜索"
                      onSearch={value => this.onSearch(value)}
                    />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem {...formItemLayout} label="设备ID">
                  {getFieldDecorator('devUuid', {
                    rules: [
                      {
                        required: true,
                      },
                    ],
                  })(<Input disabled placeholder="请输入设备ID" />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label="车牌号">
                  {getFieldDecorator('vehLicplateNo', {
                    rules: [
                      {
                        message: '请输入播放时长',
                      },
                    ],
                  })(<Input disabled placeholder="请输入车牌号" />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label="设备名称">
                  {getFieldDecorator(
                    'devName',
                    {}
                  )(<Input disabled placeholder="请输入设备名称" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem {...formItemLayout} label="公司">
                  {getFieldDecorator(
                    'compName',
                    {}
                  )(<Input disabled placeholder="请输入公司名称" />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label="司机">
                  {getFieldDecorator('mainDriver', {})(<Input disabled placeholder="请输入司机" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem {...formItemLayout} label="报修人">
                  {getFieldDecorator('reporter', {
                    rules: [
                      {
                        required: true,
                        message: '请输入报修人',
                      },
                    ],
                  })(<Input placeholder="请输入报修人" />)}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem {...formItemLayout} label="单位">
                  {getFieldDecorator('orgName', {
                    rules: [
                      {
                        required: true,
                        message: '请输入单位',
                      },
                    ],
                  })(<Input placeholder="请输入单位" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem {...formItemLayout} label="问题描述">
                  {getFieldDecorator('problemDescr', {
                    rules: [
                      {
                        required: true,
                        message: '请输入问题描述',
                      },
                    ],
                  })(<Input placeholder="请输入问题描述" />)}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem {...formItemLayout} label="问题图片">
                  <Upload
                    headers={{
                      'X-Requested-With': null,
                    }}
                    fileList={this.state.picUrlsArray}
                    onChange={this.handleChange}
                    multiple
                    action={cityUrls['maintain'] + '/vehad/v1/uploadFile'}
                  >
                    <Button>
                      <Icon type="upload" /> 上传图片
                    </Button>
                  </Upload>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <FormItem {...formItemLayout} label="问题视频">
                  <Upload
                    headers={{
                      'X-Requested-With': null,
                    }}
                    fileList={this.state.vidUrlsArray}
                    onChange={this.handleVidChange}
                    multiple
                    action={cityUrls['maintain'] + '/vehad/v1/uploadFile'}
                  >
                    <Button>
                      <Icon type="upload" /> 上传视频
                    </Button>
                  </Upload>
                </FormItem>
              </Col>
            </Row>
            <Row style={{ alignItems: 'center', display: 'flex', justifyContent: 'center' }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                提交
              </Button>
            </Row>
          </Form>
          <SelectDev
            modalVisible={this.state.modalVisible}
            dispatch={this.props.dispatch}
            data={devlist}
            handleModalVisible={this.setVisible}
            setFormValue={this.setFormValue}
          />
        </Card>
      </PageHeaderLayout>
    );
  }
}
